// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/common/base/bloom_filter.h>
#include <pollux/core/query_config.h>
#include <pollux/functions/macros.h>

namespace kumo::pollux::functions::sparksql {
    template<typename T>
    struct BloomFilterMightContainFunction {
        POLLUX_DEFINE_FUNCTION_TYPES(T);

        using Allocator = std::allocator<uint64_t>;

        void initialize(
            const std::vector<TypePtr> & /*inputTypes*/,
            const core::QueryConfig &,
            const arg_type<Varbinary> *serialized,
            const arg_type<int64_t> *) {
            if (serialized != nullptr) {
                bloomFilter_.merge(serialized->str().c_str());
            }
        }

        MELON_ALWAYS_INLINE void
        call(bool &result, const arg_type<Varbinary> &, const int64_t &input) {
            result = bloomFilter_.isSet()
                         ? bloomFilter_.mayContain(melon::hasher<int64_t>()(input))
                         : false;
        }

    private:
        BloomFilter<Allocator> bloomFilter_;
    };
} // namespace kumo::pollux::functions::sparksql
